package com.chatplus.application.listener.pay;

import com.chatplus.application.common.constant.RedisPrefix;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.domain.entity.orders.OrderEntity;
import com.chatplus.application.domain.entity.pay.PayRequestEntity;
import com.chatplus.application.enumeration.OrderStatusEnum;
import com.chatplus.application.enumeration.PayStatusEnum;
import com.chatplus.application.event.GenericEvent;
import com.chatplus.application.event.pay.PayFailEvent;
import com.chatplus.application.event.pay.PaySuccessEvent;
import com.chatplus.application.event.pay.dto.PayRequestEvent;
import com.chatplus.application.service.orders.OrderService;
import com.chatplus.application.service.pay.IPayRequestService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.redisson.api.RedissonClient;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.time.Instant;

@Component
public class PayResultEventListener {
    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(PayResultEventListener.class);

    private final OrderService orderService;
    private final ObjectMapper objectMapper;
    private final IPayRequestService payRequestService;
    private final RedissonClient redissonClient;

    public PayResultEventListener(OrderService orderService,
                                  ObjectMapper objectMapper,
                                  RedissonClient redissonClient,
                                  IPayRequestService payRequestService) {
        this.orderService = orderService;
        this.objectMapper = objectMapper;
        this.redissonClient = redissonClient;
        this.payRequestService = payRequestService;
    }

    /**
     * 支付成功后的操作
     */
    @EventListener(classes = PaySuccessEvent.class, condition = "#event.appBusinessCode.equals('CHAT')")
    @Async
    public void paySuccessEventListener(GenericEvent<PayRequestEvent> event) throws JsonProcessingException {
        LOGGER.message("收到支付成功事件").context("event", "CHAT").context("data", objectMapper.writeValueAsString(event)).info();

        PayRequestEvent payRequestEvent = event.getData();
        if (payRequestEvent == null) {
            return;
        }
        Long orderId = payRequestEvent.getOrderId();
        PayRequestEntity payRequestEntity = payRequestService.findByAppBusinessId(orderId, PayStatusEnum.SUCCESS);
        // 订单改为待打印
        OrderEntity orderEntity = orderService.getById(orderId);
        orderEntity.setStatus(OrderStatusEnum.SUCCESS);
        orderEntity.setTradeNo(payRequestEntity.getTradeTransactionId());
        orderEntity.setPayTime(payRequestEntity.getSuccessAt());
        orderService.updateById(orderEntity);
        // 清空缓存
        redissonClient.getBucket(RedisPrefix.PAY_STATUS_PREFIX+orderEntity.getId()).deleteAsync();
    }

    /**
     * 支付失败后的操作
     */
    @EventListener(classes = PayFailEvent.class, condition = "#event.appBusinessCode.equals('CHAT')")
    @Async
    public void payFailEventListener(GenericEvent<PayRequestEvent> event) throws JsonProcessingException {
        LOGGER.message("收到支付失败事件").context("event", "CHAT").context("data", objectMapper.writeValueAsString(event)).info();
        PayRequestEvent payRequestEvent = event.getData();
        if (payRequestEvent == null) {
            return;
        }
        Long orderId = payRequestEvent.getOrderId();
        OrderEntity orderEntity = orderService.getById(orderId);
        orderEntity.setStatus(OrderStatusEnum.NOT);
        orderEntity.setPayTime(Instant.now());
        orderService.updateById(orderEntity);
    }
}
